public class Solution572 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root==null){
            return false;
        }
        if (root.val==subRoot.val){
            if (compare(root,subRoot)){
                return true;
            }
        }
        return isSubtree(root.left,subRoot)||isSubtree(root.right,subRoot);
    }

    private boolean compare(TreeNode root, TreeNode subRoot) {
        if ((root==null && subRoot!=null) || (root!=null && subRoot==null)){
            return false;
        }
        if (root == null){
            return true;
        }
        if (root.val!=subRoot.val){
            return false;
        }
        return compare(root.left,subRoot.left)&&compare(root.right,subRoot.right);
    }

    public static void main(String[] args) {
        System.out.println(new Solution572().isSubtree(new TreeNode(3,new TreeNode(4,new TreeNode(1),new TreeNode(2)),new TreeNode(5)),new TreeNode(4,new TreeNode(1),new TreeNode(2))));
    }
}
